<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var price = prompt('请输入总金额')
        var goodsP = prompt('请输入价格列表')
        //输入的金额转成数字
        price = Number(price)
        //通过空格切割成数组
        goodsP = goodsP.split(/\s+/)
        //转成升序价格数组
        goodsP.sort(function (a, b) {
            return a - b
        })
        //已购买的商品总价
        let sum = 0
        //已购买价格的单价数组
        let newArr=[]
        console.log(goodsP);
        //数组中的价格都为字符串格式不好用于比较计算 需要转成数组格式
        let goodsPri
        for (let i = 0; i< goodsP.length; i++) {
            goodsPri=Number(goodsP[i])
            if(sum+goodsPri<=price){
                sum += goodsPri
                newArr.push(goodsPri)
            }else{
                break
            }
        }
        let div=document.createElement('div')
        div.innerHTML='总金额为:'+price+'元<br/>可以购买的商品是:'+goodsP+'<br/>'+'购买的商品数量:'+newArr.length+'<br/>购买的商品为:'+newArr.join()+'<br/>总花费:'+sum
        document.body.appendChild(div)
        
    </script>
</body>

</html>